﻿//uploader for browser which support HTML5 drag & drop upload
CloudDisk.DdUploader = (function(){
    var el = $('<div class="dd-uploader"></div>');
    el.html(['<div class="dialog-frame">',
	        '<div class="dialog-holder">',
			    '<div class="dialog-text">将文件拖放到此处，或直接从你的电脑上选择文件<div class="swf-uploader-btn"><span id="swfUploaderBtn">选择文件</span></div></div>',
			'</div>',
			'<div class="button-ct"><button>关闭</button></div>',
		'</div>'].join(''));
    var tests = {
      filereader: typeof FileReader != 'undefined',
      dnd: 'draggable' in document.createElement('span'),
      formdata: !!window.FormData,
      progress: "upload" in new XMLHttpRequest
    }, 
    support = {
      filereader: document.getElementById('filereader'),
      formdata: document.getElementById('formdata'),
      progress: document.getElementById('progress')
    },
    acceptedTypes = {
      'image/png': true,
      'image/jpeg': true,
      'image/gif': true
    },

    fileupload = document.getElementById('upload');

	var fileQueue = [];
	
	var isUploading = false;
	
	var xhr = new XMLHttpRequest(); 
	
	var uploadStartHandler = null;
	
	var idCounter = 0;
	
	var formData = tests.formdata ? new FormData() : null;

	function genTaskId(){
	    return 'ddupload_file_' + ++idCounter;
	}

	function startUpload(){
	    if(fileQueue.length > 0){
		    var file = fileQueue.shift();

			isUploading = true;
					  
		    xhr.onload = function() {
			    file.progress = '完成';
			    CloudDisk.UploadProgressDialog.update(file);
			    startUpload();
		    };

		    xhr.upload.onprogress = function (event) {
			    if(CloudDisk.UploadProgressDialog.isTaskRemoved(file.id)){//task already removed from progress dialog
				    xhr.abort();
				    startUpload();
				} else if (event.lengthComputable) {
			        var complete = (event.loaded / event.total * 100 | 0);
			        file.progress = complete + '%';
			        CloudDisk.UploadProgressDialog.update(file);
		        }
		    }
			
			xhr.onerror = function (event) {
				file.progress = '失败';
				CloudDisk.UploadProgressDialog.update(file);
				xhr.abort();	
				startUpload();
		    }

			var formData = new FormData();
			formData.append('file', file);
			xhr.open("POST", CloudDisk.Setting.UPLOAD_URL); 
			xhr.send(formData); 
		} else {
		    isUploading = false;
		}
	}
	
	function readfiles(files) {
		for (var i = 0; i < files.length; i++) {
			files[i].id = genTaskId();
			fileQueue.push(files[i]);
			CloudDisk.UploadProgressDialog.addTask({
				id: files[i].id,
				size: files[i].size,
				name: files[i].name
			});
	    }
        startUpload();
	}

	return {
	    init: function(){
		    el.appendTo(document.body);
		    var that = this;
			var holder = el.find('.dialog-holder')[0];
			if (tests.dnd) { 
			  holder.addEventListener('dragenter', function(e){
			      e.stopPropagation();
				  e.preventDefault();
			  }, false);
			  holder.addEventListener('dragover', function(e){
			      e.stopPropagation();
				  e.preventDefault();
				  $(this).addClass('hover');
			  }, false);
			  holder.addEventListener('dragleave', function(e){
			      e.stopPropagation();
				  e.preventDefault();
				  $(this).removeClass('hover');
			  }, false);
			  holder.addEventListener('drop', function(e){
			      e.stopPropagation();
				  e.preventDefault();
				  $(this).removeClass('hover');
				  that.hide();
				  CloudDisk.UploadProgressDialog.show();
				  readfiles(e.dataTransfer.files);
			  }, false);
			  holder.addEventListener('dragend', function(e){
			      e.stopPropagation();
				  e.preventDefault();
				  $(this).removeClass('hover');
			  }, false);

			} else {
			  holder.innerHTML = 'Drag&drop upload not supported in this browser!';
			}
			
			
			el.find('button').click(function(){
				that.hide();
			});
			
			//provide another solution for user who don't like drag&drop upload
			CloudDisk.SwfUploader.init({
				text: '选择文件',
				textStyle: ".theFont { font-size:18px; text-decoration:underline;color:#0000ff;cursor:pointer;}",
				leftTextPadding: 0,
				topTextPadding: 0,
				buttonId: 'swfUploaderBtn',
				width: 100,
				height: 30,
				uploadStartHandler: function(){
				    CloudDisk.DdUploader.hide();
				}
			});

		},
		
		show: function(){
		    el.show();
		    CloudDisk.Util.showMask();
		},
		
		hide: function(){
		    el.hide();
			CloudDisk.Util.hideMask();
		}
	};
})();